<?php

namespace app\agent\controller;

use app\models\{AgentArea, Agent as Agents, Region, AgentLog, Subcate, Cate, Product, Riderlist, RiderStreet, Withdraw, Promo, Config, Order};
use think\Db;
use think\Validate;
use app\facade\Mns;
use EasyWeChat\Factory;
use app\facade\Redis;


class Agent extends Base
{

    public function sendmess()
    {
        $CheckCode = (new Mns())->send($this->request->agent['mobile']);
        if (!$CheckCode) {
            return json(['code' => 1, 'msg' => '发送失败,请重试']);
        }
        return json(['code' => 200, 'msg' => '短信已发送至手机' . $this->request->agent['mobile']]);
    }

    public function promo()
    {
        if ($this->request->isAjax()) {
            $model = new Promo();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $list = (new Promo())->where('agentid', $this->request->agent['id'])->where('sxtime', '<=', date('Y-m-d H:i:s'))->select();
            foreach ($list as $promo) {
                (new Promo())->where('id', $promo['id'])->update(['status' => 2]);
            }
            return view(null, [
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }

    public function promo_alert()
    {
        $id = $this->request->get('id/d', 0);
        $row = (new Promo())->where(['id' => $id])->find();
        if (empty($row)) {
            return view();
        }
        $name = 'promo' . $id . '.png';
        $qcode = url('/uploads/promo/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/promo/";
        $url = '';
        if (!file_exists($path . $name)) {
            try {
                if (!is_dir($path)) {
                    mkdir($path, 0777, true);
                }
                $config = config('wechat.');
                $app = Factory::miniProgram($config);
                $rm = $app->app_code->getUnlimit('promoid=' . $id, [
                    'page'  => 'pages/index/getCoupon',
                    'auto_color' => false,
                    'line_color' => [
                        'r' => 254,
                        'g' => 117,
                        'b' => 50,
                    ],
                    'width' => 400
                ]);
                if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                    $rm->save($path, $name);
                }
                $url = $qcode;
            } catch (\Exception $e) {
                //dump($e->getMessage());
            }
        } else {
            $url = $qcode;
        }
        return view('', [
            'url' => $url
        ]);
    }

    public function promo_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'people' => 'require|gt:0',
                'contents' => 'require|length:10,150',
                'sxtime' => 'require',
            ], [
                'title.require' => '活动不能为空',
                'people.require' => '参与人不能为空',
                'people.gt' => '参与人数必须大于0',
                'contents.require' => '活动不能为空',
                'contents.length' => '区域说明长度请控制在10-150字符',
                'sxtime.require' => '活动结束时间不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!is_array($data['coupon'])) {
                return json(['code' => 1, 'msg' => '优惠券数据出错']);
            }
            $data['coupon'] = json_encode($data['coupon'], true);
            $data['agentid'] = $this->request->agent['id'];
            if (empty($data['id'])) {
                $res = (new Promo())->allowfield(true)->save($data);
            } else {
                $res = (new Promo())->allowfield(true)->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Promo())->where(['id' => $id])->find();
            if ($row) {
                $row['coupon'] = json_decode($row['coupon'], true);
            }
            $product = (new Product())->where(['agentid' => $this->request->agent['id'], 'isdel' => 1])->field('id,title,price')->select();
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
                'product' => $product
            ]);
        }
    }


    public function withdraw()
    {
        if ($this->request->isAjax()) {
            $model = new Withdraw();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['user_id', '=',  $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['name|cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $agent = $this->request->agent;
            //把id存redis，防止篡改
            $name = 'getopenidagent' . $agent['id'];
            $code = rand(10000, 99999) . $agent['id'];
            Redis::setex($name, 300, $code);
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('wechat1.')['app_id'] . "&redirect_uri=https://"
                . Env('APP_API_URL') . "/Other/getOpenId?agentid=" . $agent['id'] . '&state=' . $code . '&response_type=code&scope=snsapi_userinfo#wechat_redirect';
            return view(null, [
                'agent' => $agent,
                'qrcode' => $url
            ]);
        }
    }

    public function withdraw_status()
    {
        $id = input('id');
        $status = input('status/s', '0');
        if (!empty($id)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据状态错误']);
            }
            $model = new Withdraw();
            $cate = $model->where(['id' => $id, 'user_id' => $this->request->agent['id']])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            if ($cate['status'] != 1) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据已审核，无需重复审核']);
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => $status]);
                if ($status == 3) {
                    (new Agents())->MoneyEdit($cate['user_id'], 3, $cate['money'], '取消提现', $cate['id']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function withdraw_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|egt:100|float',
                'name' => 'require',
                'cards' => 'require',
                'bank' => 'require',
                'smscode' => 'require'
            ], [
                'money.require' => '提现金额不能为空',
                'money.gt' => '提现金额不能低于100',
                'money.float' => '提现金额数据不正确',
                'name.require' => '用户名不能为空',
                'cards.require' => '银行卡号不能为空',
                'bank.require' => '所属银行不能为空',
                'smscode.require' => '验证码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($this->request->agent['money'] < $data['money']) {
                return json(['code' => 1, 'msg' => '可提现金额不足']);
            }
            if (!(new Mns())->checkCode($data['smscode'], $this->request->agent['mobile'])) {
                return json(['code' => 1, 'msg' => '验证码错误']);
            }
            $fee = $this->request->agent['handfee'] ?? 0.7;
            $data['fee'] = round($data['money'] * $fee / 100, 2);
            if ($data['money'] < $data['fee']) {
                return json(['code' => 1, 'msg' => '提现金额不足手续费金额，不可提现']);
            }
            $data['user_id'] = $this->request->agent['id'];
            Db::startTrans();
            try {
                (new Withdraw())->allowfield(true)->save($data);
                (new Agents())->MoneyEdit($this->request->agent['id'], 2, -$data['money'], '发起提现', 0);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        } else {
            return view('', [
                'money' => $this->request->agent['money'],
                'fee' => $this->request->agent['handfee'] ?? 0.7,
            ]);
        }
    }

    public function withdraw_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|egt:100|float',
                'name' => 'require',
                'bank' => 'require',
                'smscode' => 'require'
            ], [
                'money.require' => '提现金额不能为空',
                'money.gt' => '提现金额不能低于100',
                'money.float' => '提现金额数据不正确',
                'name.require' => '用户名不能为空',
                'bank.require' => '所属银行不能为空',
                'smscode.require' => '验证码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($this->request->agent['money'] < $data['money']) {
                return json(['code' => 1, 'msg' => '可提现金额不足']);
            }
            if (!(new Mns())->checkCode($data['smscode'], $this->request->agent['mobile'])) {
                return json(['code' => 1, 'msg' => '验证码错误']);
            }
            $fee = $this->request->agent['handfee'] ?? 0.7;
            $data['fee'] = round($data['money'] * $fee / 100, 2);
            if ($data['money'] < $data['fee']) {
                return json(['code' => 1, 'msg' => '提现金额不足手续费金额，不可提现']);
            }
            $data['type'] = 2;
            $data['user_id'] = $this->request->agent['id'];
            Db::startTrans();
            try {
                (new Withdraw())->allowfield(true)->save($data);
                (new Agents())->MoneyEdit($this->request->agent['id'], 2, -$data['money'], '发起提现', 0);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        } else {
            return view('', [
                'money' => $this->request->agent['money'],
                'fee' => $this->request->agent['handfee'] ?? 0.7,
            ]);
        }
    }

    public function rider()
    {
        if ($this->request->isAjax()) {
            $model = new Riderlist();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['mobile|name|cards', 'like', '%' . $post['title'] . '%'];
            }
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $where[] = ['id', 'in', $riderid];
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            if (!empty($post['street'])) {
                $where[] = ['street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['province', '=', $post['province']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['count']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->count();
                $lists['total']  = (new Order())->where(['orderid' => $lists['id'], 'status' => 4])->sum('total');
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select()
            ]);
        }
    }


    public function rider_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
            ], [
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            } elseif (isset($data['password'])) {
                unset($data['password']);
            }
            $res = (new Riderlist())->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Riderlist())->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function rider_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Riderlist();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                (new RiderStreet())->where(['riderid' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet()
    {
        if ($this->request->isAjax()) {
            $model = new RiderStreet();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['rs.agentid', '=', $this->request->agent['id']];
            if (!empty($post['rider'])) {
                $where[] = ['rs.riderid', '=', $post['rider']];
            }
            if (!empty($post['title'])) {
                $where[] = ['r.mobile|r.name|r.cards', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['r.status', '=', $post['status']];
            }
            if (!empty($post['street'])) {
                $where[] = ['rs.street', '=', $post['street']];
            } elseif (!empty($post['area'])) {
                $where[] = ['rs.area', '=', $post['area']];
            } elseif (!empty($post['city'])) {
                $where[] = ['rs.city', '=', $post['city']];
            } elseif (!empty($post['province'])) {
                $where[] = ['rs.province', '=', $post['province']];
            }
            $count = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->alias('rs')->join('riderlist r', 'rs.riderid = r.id')
                ->where($where)->order(['rs.status' => 'asc', "rs.id" => 'desc'])->field('rs.*,r.mobile,r.name,r.cards,r.positive,r.negative')->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $address = getdrees($lists['street'], 2);
                $lists['province_text'] = $address['province'];
                $lists['city_text'] = $address['city'];
                $lists['area_text'] = $address['area'];
                $lists['street_text'] = $address['street'];
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select()
            ]);
        }
    }


    public function riderstreet_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require'
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            $data['status'] = 2;
            //查询是否有当前街道添加权限
            $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
            if (empty($ishave) || $ishave == 1) {
                return json(['code' => 1, 'msg' => '操作失败,您无该街道操作权限']);
            }
            //查询负责区域是否已存在
            $riderstreet = (new RiderStreet())->where([
                'riderid' => $data['riderid'],
                'street' => $data['street']
            ])->find();

            if (!empty($riderstreet)) {
                $res = (new RiderStreet())->allowfield(true)->save($data, ['id' => $riderstreet['id']]);
            } else {
                $res = (new RiderStreet())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $rider = (new Riderlist())->where(['id' => $riderid])->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider
            ]);
        }
    }


    public function riderstreet_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'riderid' => 'require',
                'street' => 'require'
            ], [
                'riderid.require' => '师傅不能为空',
                'street.require' => '街道不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (count($data['street']) <= 0) {
                return json(['code' => 1, 'msg' => '请选择街道']);
            }
            $data['agentid'] = $this->request->agent['id'];
            try {

                foreach ($data['street'] as $street) {
                    //查询负责区域是否已存在
                    $riderstreet = (new RiderStreet())->where([
                        'riderid' => $data['riderid'],
                        'street' => $street
                    ])->find();
                    //查询是否有当前街道添加权限
                    $ishave = geauthagents($data['agentid'], $data['street'], 0, 0);
                    if (empty($ishave) || $ishave == 1) {
                        continue;
                    }
                    $geo = getdrees($street, 3);
                    if (!empty($riderstreet)) {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $geo['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ], ['id' => $riderstreet['id']]);
                    } else {
                        (new RiderStreet())->allowfield(true)->save([
                            'agentid' => $geo['agentid'],
                            'riderid' => $data['riderid'],
                            'province' => $geo['province'],
                            'city' => $geo['city'],
                            'area' => $geo['area'],
                            'street' => $geo['street'],
                            'status' => 2
                        ]);
                    }
                }
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            $row = [];
            $province = (new Region())->where(['level' => 1])->select();
            $riderid = (new RiderStreet())->distinct(true)->where(['agentid' => $this->request->agent['id']])->column('riderid');
            $rider = (new Riderlist())->where(['id' => $riderid])->field('id,name,mobile')->select();
            $riderid = $this->request->get('riderid/d', 0);
            if (!empty($riderid)) {
                $row['riderid'] = $riderid;
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'rider' => $rider
            ]);
        }
    }

    public function riderstreet_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new RiderStreet();
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function riderstreet_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        $status = input('status/d', 0);
        if (!empty($id) && !empty($field)) {
            if ($status != 2 && $status != 3) {
                return json(['code' => 1, 'data' => [], 'msg' => '操作状态错误，请刷新页面重试']);
            }
            $model = new RiderStreet();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['subcate'])) {
                $where[] = ['subcate', '=', $post['subcate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            if (!empty($post['ishot'])) {
                $where[] = ['ishot', '=', $post['ishot']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['type'] =  config()['config']['type'][$lists['type']];
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
                $lists['subcate_name'] = (new Subcate())->where(['id' => $lists['subcate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select()
            ]);
        }
    }


    public function product_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'cate' => 'require',
                'subcate' => 'require',
                'type' => 'require',
            ], [
                'title.require' => '标题不能为空',
                'cate.require' => '分类不能为空',
                'subcate.require' => '子分类不能为空',
                'type.require' => '类型不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            if (!empty($data['id'])) {
                $res = (new Product())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Product())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Product())->where('id', $id)->find();
            $subcate = [];
            if (!empty($row)) {
                $where[] = ['cate', '=', $row['cate']];
                $where[] = ['agentid', '=', $row['agentid']];
                $subcate = (new Subcate())->where($where)->select();
            }
            return view('', [
                'row' => $row,
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select(),
                'subcate' => $subcate,
            ]);
        }
    }

    public function product_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Product();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function product_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Product();
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update(['isdel' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function subcate()
    {
        if ($this->request->isAjax()) {
            $model = new Subcate();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['title'])) {
                $where[] = ['name', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["sort" => "desc", "id" => 'desc'])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select()
            ]);
        }
    }


    public function subcate_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'cate' => 'require'
            ], [
                'cate.require' => '类型不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            $data['images'] = !empty($data['images']) ? $data['images'] : '';
            if (!empty($data['id'])) {
                $res = (new Subcate())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Subcate())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Subcate())->where('id', $id)->find();
            return view('', [
                'row' => $row,
                'cate' => (new Cate())->field('id,name,isshow')->order('sort desc')->select(),
            ]);
        }
    }

    public function subcate_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Subcate();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id, 'agentid' => $this->request->agent['id']])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function subcate_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Subcate();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->delete();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function agentlog()
    {
        if ($this->request->isAjax()) {
            $model = new AgentLog();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['types'])) {
                $where[] = ['types', '=', $post['types']];
            }
            $where[] = ['user_id', '=', $this->request->agent['id']];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
            ], [
                'mobile.require' => '手机不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                $this->result([], 1, '手机格式不正确');
            }
            $data['id']  = $this->request->agent['id'];
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            if (!empty($data['accounts'])) {
                unset($data['accounts']);
            }
            $data['levelopen'] = $data['levelopen'] ?? 1;
            if ($data['levelopen'] == 2) {
                if ($data['levelrate'] < 1 || $data['levelrate'] > 100) {
                    return json(['code' => 1, 'data' => [], 'msg' => '折扣率范围不能低于1且不能超过100']);
                }
            }
            $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->agent['id'];
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function agentarea()
    {

        if ($this->request->isAjax()) {
            $model = new AgentArea();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($post['type'])) {
                $where[] = ['type', '=', $post['type']];
                switch ($post['type']) {
                    case '2':
                        if (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '3':
                        if (!empty($post['area'])) {
                            $where[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    case '4':
                        if (!empty($post['street'])) {
                            $where[] = ['street', '=', $post['street']];
                        } elseif (!empty($post['area'])) {
                            $where[] = ['area', '=', $post['area']];
                        } elseif (!empty($post['city'])) {
                            $where[] = ['city', '=', $post['city']];
                        } elseif (!empty($post['province'])) {
                            $where[] = ['province', '=', $post['province']];
                        }
                        break;
                    default:
                        break;
                }
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '无';
                $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '无';
                $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '无';
                $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, [
                'province' => (new Region())->where(['level' => 1])->select()
            ]);
        }
    }
}
